package com.service.test;

import java.net.URI;
import java.net.URLEncoder;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.service.db.DbConnectionManager;
import com.service.db.PooledConnection;
import com.service.other.Logger;
import com.service.tools.Tools;

/**
 * 宁波 车辆监控接口调试
 * @author Administrator
 *
 */
public class MakeSendTrackData {
	
	private static String json;
	
	private static List<TestBean> list;
	
	@SuppressWarnings("unused")
	private static int Count = 0;

	public static void main(String[] args) {
		
//		list = new ArrayList<TestBean>();
//		getLngLat();
//		System.out.println("数据加载完成");
//		
//		for (TestBean bean : list) {
//			System.out.println(Count + ": " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//			func(bean);
//			if (Count == 3599)
//				return;
//			try {
//				Thread.sleep(20000);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
		
		String url = "http://garservice.nbzhhw.com/webservice/CommntInfoService.asmx/GetCommntInfo?jsonMaram={\"MSKey\":\"BJCYWEIGHTsystem08012015\"}";
		doGetStr(url);
		
	}
	
	@SuppressWarnings("unused")
	private static void func(TestBean bean) {
		try {
			json = null;
			json = MakeSendTrackData.getJson(bean);
			StringBuilder builder = new StringBuilder();
			builder.append("http://garservice.nbzhhw.com/webservice/CarTrackDataService.asmx/SendTrackData?jsonMaram=");
			URI localURI = new URI(builder.toString() + URLEncoder.encode("{" + json + "}","UTF-8"));
			String url = localURI.toASCIIString();
			doGetStr(url);
		} catch (Exception e) {
			Logger.err(e);
		} finally {
			Count++;
		}
	}
	
	/**
	 * 用于给拼接Json字符串
	 * @return
	 */
	private static Object[] getParamsForJson(TestBean bean) {
		Object[] arrs = new Object[16];
		arrs[0] = "\"" + "BJCYWEIGHTsystem08012015" + "\""; // msKey 秘钥
		arrs[1] = "\"" + "浙FF0930" + "\""; // CarNo 车辆编号
		arrs[2] = "\"" + "浙FF0930" + "\""; // PlateNo 车牌号
		arrs[3] = "\"" + "11150800476" + "\""; // DeviceNo 设备编号
		arrs[4] = "\"" + String.valueOf(bean.lng) + "\""; // Lng 经度
		arrs[5] = "\"" + String.valueOf(bean.lat) + "\""; // Lat 纬度
		arrs[6] = "\"" + String.valueOf(Tools.round(bean.direction, 0)) + "\""; // Direction 方向
		arrs[7] = "\"" + String.valueOf(bean.speed) + "\""; // Speed 当前速度
		arrs[8] = "\"" + String.valueOf(bean.oilAmtCal) + "\""; // Oil 实际油量
		arrs[9] = "\"" + String.valueOf(bean.totalMile) + "\""; // Mileage 累计里程
		arrs[10] = "\"" + String.valueOf(1) + "\""; // TagUp 装载标志 1装载 0常态
		arrs[11] = "\"" + String.valueOf(0) + "\""; // TagDown 卸载标志 1卸载 0常态
		arrs[12] = "\"" + 0 + "\""; // 主电源断电标志 1断电 0通电
		arrs[13] = "\"" + 0 + "\""; // 0 GPS正常  1 GPS开路
		arrs[14] = "\"" + 0 + "\""; // 是否安装了油杆，1是未安装，0是已安装
		arrs[15] = "\"" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\""; // GPS时间
		return arrs;
	}
	
	public static String getJson(TestBean bean) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("\"MSKey\":{0},");
		buffer.append("\"CarNo\":{1},");
		buffer.append("\"PlateNo\":{2},");
		buffer.append("\"DeviceNo\":{3},");
		buffer.append("\"Lng\":{4},");
		buffer.append("\"Lat\":{5},");
		buffer.append("\"Direction\":{6},");
		buffer.append("\"Speed\":{7},");
		buffer.append("\"Oil\":{8},");
		buffer.append("\"Mileage\":{9},");
		buffer.append("\"TagUp\":{10},");
		buffer.append("\"TagDown\":{11},");
		buffer.append("\"TagOff\":{12},");
		buffer.append("\"TagNoGPS\":{13},");
		buffer.append("\"TagNoOil\":{14},");
		buffer.append("\"Time\":{15}");
		return MessageFormat.format(buffer.toString(), getParamsForJson(bean));
	}
	
	/**
	 * 发送数据包, 接收返回信息
	 * @param vehicle 车辆
	 * @param url 接口地址
	 */
	public static  void doGetStr(String url) {
		try {
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);
			HttpResponse response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();		
			if(entity != null){
				String result = EntityUtils.toString(entity,"GBK");
				result = result.replaceAll("&lt;","<");
				result = result.replaceAll("&gt;",">");
				xmlElements(result);
			}else{
				Logger.debug("test", "No result! Json=" + json);
			}
		} catch (Exception e) {
			Logger.debug("test", "Request failed or Response failed! Json=");
			Logger.err(e);
		}
	}
	
	/**
	 * 解析返回信息, 并记录日志
	 * @param vehicle 车辆
	 * @param xmlDoc 接口返回信息
	 */
	private static  void xmlElements(String xmlDoc){
		try {
			Document document  = DocumentHelper.parseText(xmlDoc);
			//拿到根节点
			Element root = document.getRootElement();
			String result = root.elementTextTrim("Result");
			String gpsno = "11150800476";
			if("1".equals(result)){
				Logger.debug("test",gpsno+"返回值："+result+",数据传输成功! Json=" + json);
			}else if("0".equals(result)){
				Logger.debug("test",gpsno+"返回值："+result+",数据传输失败, Json=" + json);
			}else if("9".equals(result)){
				Logger.debug("test",gpsno+"返回值："+result+",密钥不正确, Json=" + json);
			}else{
				Logger.debug("test",gpsno+"返回值："+result+",无返回值, Json=" + json);
			}
		} catch (Exception e) {
			Logger.err(e);
		}
	}
	
	@SuppressWarnings("unused")
	private static void getLngLat() {
		PooledConnection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs= null;
		String sql = "SELECT TOP 3600 Lng,Lat,Direction,Speed,OilAmtCal,TotalMile "
				+ "FROM crc_GPSSignal "
				+ "WHERE GPSNO = '11150700297'"
				+ "AND GPSTime > '2015-09-14 10:00:00' "
				+ "ORDER BY GpsTime";
		try {
			con = DbConnectionManager.getConnection();
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			TestBean bean = null;
			while (rs.next()) {
				bean = new TestBean();
				bean.lng = rs.getDouble("Lng");
				bean.lat = rs.getDouble("Lat");
				bean.direction = rs.getDouble("Direction");
				bean.speed = rs.getDouble("Speed");
				bean.oilAmtCal = rs.getDouble("OilAmtCal");
				bean.totalMile = rs.getDouble("TotalMile");
				list.add(bean);
			}
		} catch (Exception e) {
			Logger.err(e);
		} finally {
			try {
				if (null != rs)
					rs.close();
				if (null != pstmt)
					pstmt.close();
				if (null != con)
					con.close();
			} catch (Exception ex) {
				Logger.err(ex);
			}
		}
	}
	
}

class TestBean {
	
	public double lng;
	
	public double lat;
	
	public double direction;
	
	public double speed;
	
	public double oilAmtCal;
	
	public double totalMile;
	
}
